1

闭包基本上是内部函数可以访问其范围之外的变量,可用于实现隐私和创建函数工厂

定义一个数组,循环遍历这个数组并在延迟3秒后打印每个元素的索引

先看一个不正确的写法:

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function() {
    alert('The index of this number is: ' + i);
    console.log('The index of this number is: ' + i);
  }, 3000);
}

看下执行效果

clipboard.png

如上图:3秒后每次都是打印4,而不是0123

原因:因为setTimeout函数创建的是一个可以访问其外部作用域的函数(闭包),该作用域包含索引i的循环。经过3秒后,i的值已经变为4

正确的写法:
写法一:

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function(i_local){
    return function () {
      alert('The index of this number is: ' + i_local);
      console.log('The index of this number is: ' + i_local);
    }
  }(i), 3000)
}

clipboard.png

写法二:

const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  setTimeout(function() {
    alert('The index of this number is: ' + i);
    console.log('The index of this number is: ' + i);
  }, 3000);
}

clipboard.png


终极斗士
10 声望0 粉丝